$(function() {
    window.longRoomData = new Array();
    var longRoomTagsData = [];
    $('.room-tab-long').click(function () {
        var $me = $(this);
        ajaxRequest('/Home/LongRoom/getLongRoom', {hotel: window.currentHotel}, 'POST', function (data) {
            $me.blur().addClass('btn-primary').siblings().removeClass('btn-primary');
            $('#room-long').removeClass('hidden').siblings(":not(':first')").addClass('hidden');
            $('.hotel-content').removeClass('hidden');
            $('#content-panel-show').removeClass('hidden');
            data = data.data;
            if (data === false) {
                $('#longRoomListBodyEmpty').removeClass('hidden');
            } else {
                refreshLongRoomList(data);
            };
        }, function(error){
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });
    });
    var refreshLongRoomList = function (datas) {
        var roomInfos = datas;
        if (roomInfos.length === 0) {
            $('#longRoomList').html('');
            $('#longRoomListBodyEmpty').removeClass('hidden');
        } else {
            $('#longRoomListBodyEmpty').addClass('hidden');
            var templateHTML = $($('#templateLongRoom').clone().html());
            var roomsHTML = '';
            $.each(roomInfos, function (key, roomInfo) {
                templateHTML.attr('data-value', key);
                templateHTML.find('.roomTypeName').text(roomInfo.roomtype);
                var roomNameLength = roomInfo.roomname.length;
                var roomnameHTML = '';
                var roomNumbers = '';
                for (i = 0; i < roomNameLength; i++) {
                    roomNumbers += roomInfo.roomid[i] + ',';
                    roomnameHTML += '<div class="roomNameTag" data-value="' + roomInfo.roomid[i] + '">' + roomInfo.roomname[i] + '</div>';
                }
                templateHTML.find('.roomNumbers').attr('data-number', roomNumbers.slice(0, -1));
                templateHTML.find('.roomNumbers').html(roomnameHTML);
                templateHTML.find('.roomTypePrice').text(roomInfo.price);
                templateHTML.find('.roomcount').text(roomInfo.count + lang('room.jian'));
                roomsHTML += templateHTML.prop('outerHTML');
            });
            $('#longRoomList').html(roomsHTML);
        }
    };
    //长租房模态框
    var refreshLongRoom = function (modal) {
        var roomContainer = modal.find('.longRoomTypeContainer');
        var addLongRoomTemplate = $('#addLongRoomTemplate');
        var data = roomContainer.data('amos.tag');
        // 分情况渲染页面
        if (longRoomTagsData.length === 0) {
            modal.find('.longRoomTypeGroup').addClass('hidden');
        } else {
            modal.find('.longRoomTypeGroup').removeClass('hidden');
            if (!data) {
                roomContainer.tag({
                    removeAtSelected: true,
                    selectedTagClickable: false,
                    avaliable: longRoomTagsData
                }).on('beforeSelected.amos.tag', function (e, value) {
                    var templete = $(addLongRoomTemplate.clone().html());
                    tempData = value.split(" ");
                    templete.find('.tag-text').text(tempData[0]).attr('data-value', tempData[1]);
                    var container = $(this);
                    var modal = container.parents('.modal');
                    modal.find('.roomNumContainer').append(templete.prop('outerHTML'));
                    // 如果房间是最后一个就隐藏，注意是beforeSelected，所以判断是1
                    if (container.find('.tag-avaliable-container .tag').length === 1) {
                        modal.find('.longRoomTypeGroup').addClass('hidden');
                    }
                });
            } else {
                roomContainer.tag('resetAvaliable');
                roomContainer.tag('addAvaliable', longRoomTagsData);
            }
        }
    }
    // 添加长租房模态框
    $('#addLongRoomModal').on('show.bs.modal', function (e) {
        var modal = $(this);
        var params = {
            hotel: window.currentHotel,
        };
        ajaxRequest('/Home/LongRoom/getRoomList', params, 'POST', function (data) {
            var data = data.data;
            var longRoomTypeSelect = $('#longRoomTypeSelect');
            longRoomTypeSelect.children().remove();
            $('#addLongRoomNumContainer').children().remove();
            $.each(data, function (key, value) {
                longRoomTypeSelect.append("<option value='" + value.roomTypeId + "'>" + value.roomTypeName + "</option>");
                window.longRoomData[value.roomTypeId] = value.room;
            });
            longRoomTagsData = [];
            $.each(data[0].room, function (index, value) {
                longRoomTagsData.push({
                    id: value.name + ' ' + value.id,
                    name: value.name
                });
            });
            refreshLongRoom(modal);
        }, null);
    });
    //记录待添加的房间
    $('#longRoomTagContainer').on('click', '.tag', function () {
        var roomId = $(this).attr('data-value');
        var selectRoom = $.grep(longRoomTagsData, function (data) {
            if (data.id == roomId) {
                return false;
            } else {
                return true;
            }
        });
        longRoomTagsData = selectRoom;
    });
    //删除待添加的房间
    $('#addLongRoomModal').on('click', '.tag-minus', function () {
        var modal = $(this).parents('.modal');
        var roomId = $(this).siblings().attr('data-value');
        var roomName = $(this).siblings().text();
        $(this).parent().remove();
        longRoomTagsData.push({
            id: roomName + ' ' + roomId,
            name: roomName
        });
        refreshLongRoom(modal);
    });
    //选择房型
    $('#longRoomTypeSelect').change(function () {
        var longRoomTypeId = $(this).val();
        longRoomTagsData = [];
        $.each(window.longRoomData[longRoomTypeId], function (index, value) {
            longRoomTagsData.push({
                id: value.name + ' ' + value.id,
                name: value.name
            });
        });
        $('#addLongRoomNumContainer').children().remove();
        refreshLongRoom($('#addLongRoomModal'));
    });

    //添加长租房
    $('#submitLongRoomAdd').on('click', function (e) {
        var roomInfoIds = [];
        var $me = $('#submitLongRoomAdd');
        var modal = $('#addLongRoomModal');
        var inputPrice = $('#addLongRoomModal').find('.price-input');
        $('#addLongRoomNumContainer').find('.long-room-tag').each(function (k, v) {
            roomInfoIds[k] = $(this).find('.tag-text').data('value');
        });
        if (roomInfoIds.length === 0) {
            formInlineTip($(this), lang('room.select'), 0);
            return false;
        }
        var price = $('#addLongRoomPrice').val().replace(/^0(?=\d)/g, '');
        if ($.trim(price) == '' || price == 0) {
            formInlineTip($me, lang('price.select'), 0);
            return false;
        } else if (price.length != '' && !window.commonRegexp.roomTypePrice.test(price)) {
            formInlineTip($me, lang('default.payVal'), 0);
            return false;
        }
        var roomTypeId = $('#longRoomTypeSelect').val();
        var params = {
            'hotel': window.currentHotel,
            'price': price,
            'roomInfoIds': roomInfoIds,
            'roomTypeId': roomTypeId,
        }

        ajaxRequest('/Home/LongRoom/addLongRoom', params, 'POST', function (data) {
            refreshLongRoomList(data.data);
            $('#addLongRoomModal').modal('hide');
        }, null);
    });

    //修改钟点房模态框
    $('#editLongRoomModal').on('show.bs.modal', function (e) {
        var $me = $(e.relatedTarget),
            $parent = $me.parents('tr'),
            modal = $(this),
            roomTypeId = $parent.data('value'),
            priceInput = $('#editLongRoomPrice'),
        waitForDelete = {};
        waitForAdd = {};
        formInlineTip($('#submitLongRoomEdit'), '');
        $('#editLongRoomName').val($parent.find('.roomTypeName').text());
        $('#editLongRoomName').data('id', roomTypeId);
        $('#editLongRoomPrice').val($parent.find('.roomTypePrice').text());
        ajaxRequest('/Home/LongRoom/getRoomByTypeId', {
            'hotel': window.currentHotel,
            'roomTypeId': roomTypeId,
        }, 'POST', function (data) {
            var data = data.data;
            var roomContainer = modal.find('.longRoomTypeContainer');
            var addLongRoomTemplate = $('#addLongRoomTemplate');
            var templete = $(addLongRoomTemplate.clone().html());
            longRoomTagsData = [];
            var roomIds = $parent.find('.roomNumbers').data('number').toString().split(',');
            modal.find('.roomNumContainer').html('');
            $.each(data.roomInfos, function (index, value) {
                if ($.inArray(value.id, roomIds) === -1) {
                    longRoomTagsData.push({
                        id: value.name + ' ' + value.id,
                        name: value.name
                    });
                } else {
                    templete.find('.tag-text').text(value.name).attr('data-value', value.id);
                    modal.find('.roomNumContainer').append(templete.prop('outerHTML'));
                }
            });
            priceInput.val(data.longPrice);
            refreshLongRoom(modal);
        }, null, $('#submitLongRoomEdit'));
    });
    //删除已添加的房间
    window.waitForDelete = {};
    $('#editLongRoomModal').on('click', '.tag-minus', function () {
        if ($('#editLongRoomNumContainer').find('.long-room-tag').length == 1) {
            formInlineTip($('#submitLongRoomEdit'), lang('least.one'));
            return false;
        }
        var modal = $(this).parents('.modal');
        var roomId = $(this).siblings().attr('data-value');
        var roomName = $(this).siblings().text();
        var roomTypeId = modal.find('tr').data('value');
        waitForDelete[roomId] = roomId;
        $(this).parent().remove();
        longRoomTagsData.push({
            id: roomName + ' ' + roomId,
            name: roomName
        });
        refreshLongRoom(modal);
    });
    //记录已添加的房间
    window.waitForAdd = {};
    $('#editLongRoomTagContainer').on('click', '.tag', function () {
        var roomId = $(this).attr('data-value');
        var selectRoom = $.grep(longRoomTagsData, function (data) {
            if (data.id == roomId) {
                return false;
            } else {
                return true;
            }
        });
        longRoomTagsData = selectRoom;
        roomId = roomId.split(' ')[1];
        waitForAdd[roomId] = roomId;
    });
    //修改钟点房房型
    $('#submitLongRoomEdit').on('click', function () {
        var modal = $('#editLongRoomModal');
        var $me = $(this);
        var price = $('#editLongRoomPrice').val().replace(/^0(?=\d)/g, '');
        if ($.trim(price) == '' || price == 0) {
            formInlineTip($me, lang('price.select'), 0);
            return false;
        } else if (price.length != '' && !window.commonRegexp.roomTypePrice.test(price)) {
            formInlineTip($me, lang('default.payVal'), 0);
            return false;
        }
        ajaxRequest('/Home/LongRoom/saveLongRoom', {
            'hotel': window.currentHotel,
            'waitForAdd': window.waitForAdd,
            'waitForDelete': window.waitForDelete,
            'price': price,
            'roomTypeId': $('#editLongRoomName').data('id'),
        }, 'POST', function (data) {
            refreshLongRoomList(data.data);
            modal.modal('hide');
        }, null, $(this));
    });

    //删除钟点房房型
    $('#deleteLongRoomModal').on('show.bs.modal', function (e) {
        var triggerTd = $(e.relatedTarget).parents('td'),
            triggerTr = triggerTd.parents('tr');
        var roomTypeId = triggerTr.data('value');
        var roomType = triggerTr.find('.roomTypeName').html();
        var roomNum = triggerTr.find('.roomNumbers').data('roomnumber');
        $('#deleteLongRoomModal .roomType').html(roomType);
        $('#submitLongRoomDelete').data('value', roomTypeId);
    });

    // 删除房型
    $('#submitLongRoomDelete').on('click', function (e) {
        var param = {
                hotel: window.currentHotel,
                roomTypeId: $(this).data('value'),
            },
            $me = $(this);
        ajaxRequest('/Home/LongRoom/deleteLongRoom', param, 'post', function (data) {
            refreshLongRoomList(data.data);
            $('#deleteLongRoomModal').modal('hide');
        }, function (error, $obj) {
            if (typeof error.responseJSON == 'undefined') {
                formInlineTip($obj, lang('tip.networkPoor'));
            } else {
                formInlineTip($obj, error.responseJSON.info);
            }
        }, $me);
    });
});